package com.zisuyi.game.sdk.library.login

import android.content.Intent
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.weilele.mvvm.utils.fragment.addFragment

internal abstract class BaseGameLogin(fm: FragmentManager, lifecycleOwner: LifecycleOwner) :
    IGameLogin {
    protected val listeners = mutableListOf<IGameLogin.OnLoginListener>()
    protected val callFragment = GameLoginFragment(::onActivityResultByFragment)

    init {
        lifecycleOwner.lifecycle.addObserver(this)
        fm.addFragment("GameLoginGoogleImpl", callFragment)
    }

    final override fun requestLogin() {
        if (callFragment.activity == null) {
            callFragment.lifecycleScope.launchWhenStarted {
                startLogin()
            }
        } else {
            startLogin()
        }
    }

    abstract fun startLogin()

    final override fun addOnLoginListener(listener: IGameLogin.OnLoginListener) {
        if (!listeners.contains(listener)) {
            listeners.add(listener)
        }
    }

    final override fun removeOnLoginListener(listener: IGameLogin.OnLoginListener) {
        listeners.remove(listener)
    }

    override fun onDestroy() {
        super.onDestroy()
        listeners.clear()
    }

    abstract fun onActivityResultByFragment(requestCode: Int, resultCode: Int, data: Intent?)
}